/********************************************************************************
 * MailManagerAction.java
 *
 * Created by Jigar Mistry
 * Last modified Date: Aug 29, 2008 9:15:08 AM by Jigar Mistry
 * Version : 0.1
 * Copyright (c) 2008 - 2009 cyberThink Infotech Pvt. Ltd., All rights reserved.
 ********************************************************************************/

package com.printeverywhere.action;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionContext;
import com.printeverywhere.delegator.AdminServiceDelegator;
import com.printeverywhere.delegator.CommonFunctionDelegator;
import com.printeverywhere.delegator.LetterServiceDelegator;
import com.printeverywhere.delegator.MailGroupServiceDelegator;
import com.printeverywhere.delegator.UserServiceDelegator;
import com.printeverywhere.dto.GroupUser;
import com.printeverywhere.dto.Groups;
import com.printeverywhere.dto.Letters;
import com.printeverywhere.dto.User;

/**
 * The Class MailManagerAction.
 */
public class MailManagerAction extends AdminEngineManagement implements ServletRequestAware {

	/** Logger for this class. */
	private static final Logger logger = Logger
			.getLogger(MailManagerAction.class);

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	/** The action. */
	private String action;

	/** The subject. */
	private String subject;

	/** The letter. */
	private Letters letter;

	private String submit;

	private String sendMail;

	/** The letters. */
	private List<Letters> letters = LetterServiceDelegator.getList();

	/** The group list. */
	private List<Groups> groupList;

	private List<User> addSubscriberUserList;

	private List<GroupUser> groupUserList;

	/** The groupId. */
	private String groupId;

	private HttpServletRequest request;

	private String deleteGroupEmail = null;

	public String getGroupId() {
		return groupId;
	}

	public void setGroupId(String groupId) {
		this.groupId = groupId;
	}

	public List<User> getAddSubscriberUserList() {
		return addSubscriberUserList;
	}

	public void setAddSubscriberUserList(List<User> addSubscriberUserList) {
		this.addSubscriberUserList = addSubscriberUserList;
	}

	public List<Groups> getGroupList() {
		return groupList;
	}

	public void setGroupList(List<Groups> groupList) {
		this.groupList = groupList;
	}

	/**
	 * Gets the letter.
	 *
	 * @return the letter
	 */
	public Letters getLetter() {
		return letter;
	}

	/**
	 * Sets the letter.
	 *
	 * @param letter
	 *            the new letter
	 */
	public void setLetter(Letters letter) {
		this.letter = letter;
	}

	/**
	 * Gets the action.
	 *
	 * @return the action
	 */
	public String getAction() {
		return action;
	}

	/**
	 * Sets the action.
	 *
	 * @param action
	 *            the new action
	 */
	public void setAction(String action) {
		this.action = action;
	}

	/**
	 * Gets the letter information.
	 *
	 * @return the letter information
	 *
	 * @throws Exception
	 *             the exception
	 */
	public String getLetterInformation() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("getLetterInformation() - start"); //$NON-NLS-1$
		}

		prep();
		if (letter != null && letter.getLetterId() != 0) {
			if (action.equals("Delete_Letter")) {
				deleteLetter();

				if (logger.isDebugEnabled()) {
					logger.debug("getLetterInformation() - end"); //$NON-NLS-1$
				}
				letters = LetterServiceDelegator.getList();
				addActionMessage("Letter has been deleted Successfully");
				return "deleted";
			} else {
				letter = LetterServiceDelegator.getLetter(letter.getLetterId());
			}
		}

		if (logger.isDebugEnabled()) {
			logger.debug("getLetterInformation() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/**
	 * Insert or update.
	 *
	 * @return the string
	 */
	public String insertOrUpdate() {
		if (logger.isDebugEnabled()) {
			logger.debug("insertOrUpdate() - start"); //$NON-NLS-1$
		}

		if (!letterValidationSuccessful()) {
			if (logger.isDebugEnabled()) {
				logger.debug("insertOrUpdate() - end"); //$NON-NLS-1$
			}
			return INPUT;
		} else {
			if (letter.getLetterId() == 0) {
				List<Letters> lettersList = LetterServiceDelegator
						.getLettersBySubject(letter.getSubject());

				if (lettersList != null) {
					addActionError("Letters With this Subject Name is already Exist Please try another ");
					return INPUT;
				}

				letter.setAdmin(AdminServiceDelegator.getAdminByName("admin"));
				LetterServiceDelegator.insertLetter(letter);
				addActionMessage("Letter added Successfully ");
				letter.setSubject("");
				letter.setMessage("");
				letter.setLetterId(0);
				letters = LetterServiceDelegator.getList();
			} else {
				letter.setAdmin(AdminServiceDelegator.getAdminByName("admin"));
				LetterServiceDelegator.updateLetter(letter);
				addActionMessage("Letter Updated Successfully ");
			}
		}

		if (logger.isDebugEnabled()) {
			logger.debug("insertOrUpdate() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/**
	 * Delete letter.
	 *
	 * @return the string
	 */
	public void deleteLetter() {
		if (logger.isDebugEnabled()) {
			logger.debug("deleteLetter() - start"); //$NON-NLS-1$
		}

		LetterServiceDelegator.deleteLetter(LetterServiceDelegator
				.getLetter(letter.getLetterId()));
		letter = null;

		if (logger.isDebugEnabled()) {
			logger.debug("deleteLetter() - end"); //$NON-NLS-1$
		}
	}

	/**
	 * Validation successful.
	 *
	 * @return true, if successful
	 */
	private boolean letterValidationSuccessful() {
		if (logger.isDebugEnabled()) {
			logger.debug("letterValidationSuccessful() - start"); //$NON-NLS-1$
		}

		if (letter.getSubject() == null
				|| letter.getSubject().trim().length() < 1) {
			addActionError("Subject is required");
			return false;
		}
		if (letter.getSubject().trim().length() > 50) {
			addActionError("Subject name is too long Please try another");
			return false;
		}
		if (letter.getMessage() == null
				|| letter.getMessage().trim().length() < 1) {
			addActionError("Message is required");
			return false;
		}

			return true;
	}

	/**
	 * Prep.
	 */
	@SuppressWarnings("unchecked")
	private void prep() {
		if (logger.isDebugEnabled()) {
			logger.debug("prep() - start"); //$NON-NLS-1$
		}

		letters = LetterServiceDelegator.getList();
		Map<String, Object> session = ActionContext.getContext().getSession();
		session.put("letters", letters);

		if (logger.isDebugEnabled()) {
			logger.debug("prep() - end"); //$NON-NLS-1$
		}
	}

	/**
	 * Gets the letters.
	 *
	 * @return the letters
	 */
	public List<Letters> getLetters() {
		return letters;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.opensymphony.xwork2.ActionSupport#execute()
	 */
	public String execute() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("execute() - start"); //$NON-NLS-1$
		}

		if (logger.isDebugEnabled()) {
			logger.debug("execute() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	public String showUserMailingList() throws Exception{

		if (logger.isDebugEnabled()) {
			logger.debug("showUserMailingList() - start"); //$NON-NLS-1$
		}

		addSubscriberUserList = UserServiceDelegator.getList();

		if (logger.isDebugEnabled()) {
			logger.debug("showUserMailingList() - end"); //$NON-NLS-1$
		}

		return SUCCESS;
	}

	public String sendUserMailingList() throws Exception{

		if (logger.isDebugEnabled()) {
			logger.debug("sendUserMailingList() - start"); //$NON-NLS-1$
		}

		addActionMessage("Send Mail to Registered User");
		addSubscriberUserList = UserServiceDelegator.getList();

		if (logger.isDebugEnabled()) {
			logger.debug("sendUserMailingList() - end"); //$NON-NLS-1$
		}

		return SUCCESS;
	}

	/**
	 * Show manage letters.
	 *
	 * @return the string
	 *
	 * @throws Exception
	 *             the exception
	 */
	public String showManageLetters() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("showManageLetters() - start"); //$NON-NLS-1$
		}

		letters = LetterServiceDelegator.getList();

		if (logger.isDebugEnabled()) {
			logger.debug("showManageLetters() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	public void populateGroupList() throws Exception{
		groupList = MailGroupServiceDelegator.getGroupList();
		addSubscriberUserList = UserServiceDelegator.getList();

		for (Groups groups : groupList) {
			groups.setName(new StringBuffer(groups.getName()).append(" (")
					.append(
							MailGroupServiceDelegator
									.countGroupSubscriberById(groups
											.getGroupId())).append(")")
					.toString());
		}

	}

	/**
	 * Show manage mail list.
	 *
	 * @return the string
	 *
	 * @throws Exception
	 *             the exception
	 */
	public String showManageMailList() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("showManageMailList() - start"); //$NON-NLS-1$
		}

		populateGroupList();

		if (logger.isDebugEnabled()) {
			logger.debug("showManageMailList() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	public String getGroupListMail() throws Exception {

		if (logger.isDebugEnabled()) {
			logger.debug("getGroupListMail() - start"); //$NON-NLS-1$
		}

		populateGroupList();

		if (groupId == null) {
			addActionError("Please Select Group for Load Subscriber Email");
			return INPUT;
		} else {

			groupUserList = MailGroupServiceDelegator.getGroupUserByGroupId(Integer.parseInt(groupId));

			if (logger.isDebugEnabled()) {
				logger.debug("getGroupListMail() - end"); //$NON-NLS-1$
			}
		return SUCCESS;
		}
	}

	public String deleteEmailList() throws Exception {

		if (logger.isDebugEnabled()) {
			logger.debug("deleteEmailList() - start"); //$NON-NLS-1$
		}

		if(groupId != null && request.getParameterValues("email") != null){
			String[] selectedEmail = request.getParameterValues("email");
			for (String chkid : selectedEmail) {
				if (deleteGroupEmail == null) {
					deleteGroupEmail = chkid;
				} else {
					deleteGroupEmail = deleteGroupEmail + " , " + chkid;
				}
			}
			CommonFunctionDelegator.executeQuery("DELETE FROM GroupUser groupuser WHERE ((groupid = "
					+ groupId
					+ ") and userId IN ("
					+ deleteGroupEmail
					+ "))");
			populateGroupList();
			groupUserList = MailGroupServiceDelegator.getGroupUserByGroupId(Integer.parseInt(groupId));
			addActionMessage("User Email has been deleted from List");
		}else{
			populateGroupList();
			groupUserList = MailGroupServiceDelegator.getGroupUserByGroupId(Integer.parseInt(groupId));
			addActionError("Please Select Email for Delete from group");
			return INPUT;
		}

		if (logger.isDebugEnabled()) {
			logger.debug("deleteEmailList() - end"); //$NON-NLS-1$
		}
		return SUCCESS;

	}

	/**
	 * Show delete subscribers.
	 *
	 * @return the string
	 *
	 * @throws Exception
	 *             the exception
	 */
	public String showDeleteSubscribers() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("showDeleteSubscribers() - start"); //$NON-NLS-1$
		}

		if (logger.isDebugEnabled()) {
			logger.debug("showDeleteSubscribers() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/**
	 * Show create mail list.
	 *
	 * @return the string
	 *
	 * @throws Exception
	 *             the exception
	 */
	public String showCreateMailList() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("showCreateMailList() - start"); //$NON-NLS-1$
		}

		if (logger.isDebugEnabled()) {
			logger.debug("showCreateMailList() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/**
	 * Show delete list.
	 *
	 * @return the string
	 *
	 * @throws Exception
	 *             the exception
	 */
	public String showDeleteList() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("showDeleteList() - start"); //$NON-NLS-1$
		}

		if (logger.isDebugEnabled()) {
			logger.debug("showDeleteList() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/**
	 * Show send mass email.
	 *
	 * @return the string
	 *
	 * @throws Exception
	 *             the exception
	 */
	public String showSendMassEmail() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("showSendMassEmail() - start"); //$NON-NLS-1$
		}

		populateGroupList();

		if(submit!=null && submit.contains("Send Letter")){
			addActionMessage("Unable to connet mail server");
			groupId = null;
		}
		if (logger.isDebugEnabled()) {
			logger.debug("showSendMassEmail() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/**
	 * @return the subject
	 */
	public String getSubject() {
		return subject;
	}

	/**
	 * @param subject
	 *            the subject to set
	 */
	public void setSubject(String subject) {
		this.subject = subject;
	}

	public List<GroupUser> getGroupUserList() {
		return groupUserList;
	}

	public void setGroupUserList(List<GroupUser> groupUserList) {
		this.groupUserList = groupUserList;
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	/**
	 * @return the submit
	 */
	public String getSubmit() {
		return submit;
	}

	/**
	 * @param submit the submit to set
	 */
	public void setSubmit(String submit) {
		this.submit = submit;
	}

	public String getSendMail() {
		return sendMail;
	}

	public void setSendMail(String sendMail) {
		this.sendMail = sendMail;
	}
}